package com.example.system.controller;

import cn.hutool.core.lang.tree.Tree;
import com.example.starter.util.Response;
import com.example.starter.webmvc.valid.CreateValid;
import com.example.starter.webmvc.valid.UpdateValid;
import com.example.system.constant.PM;
import com.example.system.convert.DeptConvert;
import com.example.system.dto.DeptDto;
import com.example.system.service.IDeptService;
import com.example.system.vo.DeptVo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * @author 王令
 * @since 2022-10-23
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/dept")
public class DeptController {

    private final IDeptService service;

    @PreAuthorize("hasAuthority('"+ PM.SYS_DEPT_WRITE +"')")
    @PostMapping
    public Response<Boolean> create(@RequestBody @Validated(CreateValid.class) DeptDto deptDto) {
        service.create(deptDto);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_DEPT_WRITE +"')")
    @PutMapping
    public Response<Boolean> update(@RequestBody @Validated(UpdateValid.class) DeptDto deptDto) {
        service.update(deptDto);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_DEPT_WRITE +"')")
    @DeleteMapping("/{id}")
    public Response<Boolean> deleteById(@PathVariable("id") Long id) {
        service.deleteById(id);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_DEPT_READ +"')")
    @GetMapping("/{id}")
    public Response<DeptVo> findById(@PathVariable("id") Long id) {
        return Response.ok(DeptConvert.INSTANCE.toDeptVo(service.getById(id)));
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_DEPT_READ +"')")
    @GetMapping("/tree")
    public Response<List<Tree<Long>>> listWithTree() {
        return Response.ok(service.listWithTree());
    }
}
